const {
    handleUpload,
    handleRemove,
    handlePreview,
    handleList,
} = require('../models/file')

// 上传 修改
const upload = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if(ctx.session.role === 'root'){
        ctx.body = await handleUpload({file: ctx.request.files.file, ...ctx.request.body}).catch(err => ctx.body = err);
    }else if(ctx.session.role === 'user'){
        ctx.body = await handleUpload({userId: ctx.session.id, file: ctx.request.files.file, ...ctx.request.body}).catch(err => ctx.body = err);
    }else{
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 删除
const remove = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if(ctx.session.role === 'root'){
        ctx.body = await handleRemove({...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    }else if(ctx.session.role === 'user'){
        ctx.body = await handleRemove({userId: ctx.session.id, ...ctx.params}).catch(err => ctx.body = err);
    }else{
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 预览
const preview = async (ctx, next) => {
    ctx.body = await handlePreview(ctx.params, ctx).catch(err => ctx.body = err);
}

// 列表
const list = async (ctx, next) => {
    if(ctx.session.role === 'root'){
        ctx.body = await handleList(ctx.request.query).catch(err => ctx.body = err);
    }else if(ctx.session.role === 'user'){
        ctx.body = await handleList({userId: ctx.session.id, ...ctx.request.query}).catch(err => ctx.body = err);
    }else{
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}


module.exports = {upload, remove, preview, list}
